package com.rpay.web.interceptor.authentic.strategy;

import com.rpay.common.util.LoggerUtil;
import com.rpay.common.util.Md5Util;
import com.rpay.common.util.StringUtil;

import javax.servlet.http.HttpServletRequest;
import com.rpay.common.exception.SecurityException;

/**
 * Title：
 * Description
 *
 * @author fxg06 on 2018/4/19
 * @version 1.0
 */
public class SecretControl implements BaseAccessControl {
    /**
     * 每个请求与服务器当前时间对比，时间间隔不能超过 5 分钟
     * 5分钟 单位:毫秒  5*60*1000
     */

    private int intervalTime = 30000;
    private String secret = "IxoYxdKw";
    private String salt = "!@##@!";

    @Override
    public boolean authorize(HttpServletRequest request) throws SecurityException {
        String key = request.getParameter("key");
        String tsStr = request.getParameter("ts");

        if (StringUtil.isBlank(key)) {
            LoggerUtil.error("key is blank");
            throw new SecurityException();
        }

        if (StringUtil.isBlank(tsStr)) {
            LoggerUtil.error("ts is blank");
            throw new SecurityException();
        }
        if (!StringUtil.isNumeric(tsStr)) {
            LoggerUtil.error("please input correct timeStamp");
            throw new SecurityException();
        }

        Long ts = Long.valueOf(tsStr);
        if (Math.abs(System.currentTimeMillis() - ts) > intervalTime) {
            LoggerUtil.error("request url time invalidate");
            throw new SecurityException();
        }

        if (!isSecretValid(tsStr, key)) {
            LoggerUtil.error("key is invalidate");
            throw new SecurityException();
        }
        return true;

    }

    /**
     * 请求是否有效
     *
     * @param timestamp 时间戳
     * @param key       md5的签名
     * @return boolean
     */
    private boolean isSecretValid(String timestamp, String key) {
        return key.equals(Md5Util.encrypt(secret + salt + timestamp));
    }
}
